package org.darkforest.merchant.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.darkforest.common.services.AccountService;
import org.darkforest.common.services.StoreMsgTplService;
import org.darkforest.dao.mapper.SellerGroupMapper;
import org.darkforest.dao.mapper.SellerMapper;
import org.darkforest.model.*;
import org.darkforest.ucenter.service.MemberService;
import org.darkforest.ucenter.service.SellerService;
import org.darkforest.vo.AjaxReturnData;
import org.darkforest.vo.StoreSellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * Created by chenyu on 15/1/30.
 * 商户帐号管理控制类
 */
@RequestMapping(value="account")
@Controller
public class AccountController {
@Autowired
    AccountService accountService;
    @Autowired
    SellerGroupMapper groupMapper;
    @Autowired
    SellerMapper sellerMapper;
    @Autowired
    MemberService memberServiceImpl;
    @Autowired
    SellerService sellerService;

    @Autowired
    private StoreMsgTplService storeMsgTplService;

    /**
     * 帐号列表
     * @return
     */
    @RequestMapping(value="accountList",method = RequestMethod.GET)
    public ModelAndView accountList(HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        Seller seller = new Seller();
        seller.setStoreId(sellerVo.getStoreId());
        List accountList = accountService.findSellerByCondition(seller);
        return new ModelAndView("account/account_list", "accountList", accountList);
    }

    @RequestMapping("addAccount")
    public ModelAndView add(HttpSession session){
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        SellerGroup sellerGroup = new SellerGroup();
        sellerGroup.setStoreId(sellerVo.getStoreId());
        List groupList = groupMapper.findSellerGroupByCondition(sellerGroup);
        return new ModelAndView("account/account_add", "groupList", groupList);
    }


    @RequestMapping("doAddAccount")
    public String doAdd(String member_name,String password,String sellerName,int sellerGroupId,HttpSession session){
        StoreSellerVo sellerVo = (StoreSellerVo)session.getAttribute("sellerInfo");
        Member member = memberServiceImpl.checkUser(member_name);
        if(member==null) {
            return  "redirect:/account/accountList";
        }
        Seller seller = new Seller();
        seller.setIsAdmin((byte)0);
        seller.setMemberId(member.getMemberId());
        seller.setSellerGroupId(sellerGroupId);
        seller.setSellerName(sellerName);
        seller.setStoreId(sellerVo.getStoreId());
        accountService.insertSelective(seller);
        member.setMemberPasswd(DigestUtils.md5Hex(password));
        memberServiceImpl.updateMemberBaseInfo(member);
        return  "redirect:/account/accountList";
    }


    @RequestMapping("editAccount")
    public ModelAndView editAccount(int sellerId){
       Seller seller =  sellerMapper.selectByPrimaryKey(sellerId);
        ModelAndView m = new ModelAndView("account/account_edit","seller",seller);

        SellerGroup sellerGroup = new SellerGroup();
        sellerGroup.setStoreId(seller.getStoreId());
        List groupList = groupMapper.findSellerGroupByCondition(sellerGroup);
        m.addObject("groupList",groupList);
        return  m;
    }


    @RequestMapping("doEditAccount")
    public String doEditAccount(Seller seller){
        accountService.editSeller(seller);
        return  "redirect:/account/accountList";
    }


    @RequestMapping("deleteAccount")
    public String deleteAccount(int sellerId){
      accountService.deleteSeller(sellerId);
        return  "redirect:/account/accountList";
    }


    @RequestMapping("checkMember")
    public @ResponseBody boolean checkMember(HttpServletResponse response,String memberName) throws  Exception{
        Member member = memberServiceImpl.checkUser(memberName);
//        Member member = memberServiceImpl.checkUserAndPassword(memberName, password);
        if(member==null) {
            return false;
        }
        return true;
    }

    @RequestMapping("checkMemberSeller")
    public @ResponseBody boolean checkMemberSeller(HttpServletResponse response,HttpServletRequest request, String memberName) throws  Exception{
        Member member = memberServiceImpl.checkUser(memberName);
        if(member != null) {
            StoreSellerVo sellerVo = (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
            Seller seller = new Seller();
            //seller.setStoreId(sellerVo.getStoreId());
            seller.setMemberId(member.getMemberId());

            List<Seller> sellerList =  sellerMapper.findSellerByCondition(seller);
            if (sellerList.size() > 0) {
                for (Seller seller1:sellerList) {
                    if (sellerVo.getStoreId() != seller1.getStoreId()) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    @RequestMapping("checkSellerName")
    public void checkSellerName(HttpServletResponse response,String sellerName) throws  Exception{
       Seller seller =  sellerMapper.selectBySellerName(sellerName);
        if(seller==null) {
            response.getWriter().write("false");
            return ;
        }
        response.getWriter().write("true");
        return ;
    }




    /**
     * 帐号组
     * @return
     */
    @RequestMapping("groupList")
    public ModelAndView group(HttpServletRequest request){
       StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
       SellerGroup sellerGroup = new SellerGroup();
       sellerGroup.setStoreId(sellerVo.getStoreId());
       List groupList =  groupMapper.findSellerGroupByCondition(sellerGroup);
       return new ModelAndView("account/group_list", "groupList", groupList);
    }

    /**
     * 帐号组
     * @return
     */
    @RequestMapping("addGroup")
    public String group_add(HttpServletRequest request){
        List<StoreMsgTpl> storeMsgTplList = storeMsgTplService.findStoreMsgTplListByCondition(new StoreMsgTpl());
        request.setAttribute("allMsgTpls",storeMsgTplList);
        return "account/group_add";
    }


    /**
     * 帐号组
     * @return
     */
    @RequestMapping("doAddGroup")
    public String  saveGroup(String groupName,String[] limits,String[] smt_limits,HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        SellerGroupWithBLOBs group = new SellerGroupWithBLOBs();
        group.setGroupName(groupName);
        if(limits!=null)
             group.setLimits(Arrays.toString(limits));
        if(smt_limits!=null)
             group.setSmtLimits(Arrays.toString(smt_limits));
        group.setStoreId(sellerVo.getStoreId());
        accountService.insertGroup(group);
        return "redirect:/account/groupList";
    }

    @RequestMapping("editGroup")
    public ModelAndView  editGrop(String groupId){
        ModelAndView res = new ModelAndView("account/group_edit");
        SellerGroupWithBLOBs group = groupMapper.selectByPrimaryKey(Integer.parseInt(groupId));
        List<StoreMsgTpl> storeMsgTplList = storeMsgTplService.findStoreMsgTplListByCondition(new StoreMsgTpl());
        res.addObject("groupTemp",group);
        res.addObject("allMsgTpls",storeMsgTplList);
        res.addObject("selectedSmtLimits",group.getSmtLimits());
        return res;
    }


    @RequestMapping("doEditGroup")
    public String  doEditGrop(HttpServletRequest request ,int groupId ,String groupName,String[] limits,String[] smt_limits){
        SellerGroupWithBLOBs group = new SellerGroupWithBLOBs();
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        group.setGroupName(groupName);
        group.setGroupId(groupId);
        if(limits!=null)
            group.setLimits(Arrays.toString(limits));
        if(smt_limits!=null)
            group.setSmtLimits(Arrays.toString(smt_limits));
        group.setStoreId(sellerVo.getStoreId());
        accountService.editGroup(group);
        return "redirect:/account/groupList";
    }


    @RequestMapping("deleteGroup")
    public @ResponseBody AjaxReturnData deleteGroup(int groupId,HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");

        Seller seller= new Seller();
        seller.setSellerGroupId(groupId);
        seller.setStoreId(sellerVo.getStoreId());
        List<Seller> sellerList = sellerMapper.findSellerByCondition(seller);
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        if(sellerList.size()>0){
            ajaxReturnData.setResult(false);
            ajaxReturnData.setMessage("已关联用户，不可删除");
        }else{
            accountService.deleteGroup(groupId);
            ajaxReturnData.setResult(true);
            ajaxReturnData.setMessage("用户组删除成功");
        }
        return ajaxReturnData;
    }

    /**
     * 帐号日志
     * @return
     */
    @RequestMapping("logList")
    public ModelAndView logList(SellerLogSearchBean page,HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        page.setLogStoreId(sellerVo.getStoreId());
        accountService.selectSellerLogListByCondition(page);
        return new ModelAndView("account/logList","page",page);
    }

    @RequestMapping("toedit")
    public ModelAndView toEdit(){
        ModelAndView view = new ModelAndView("account/account_set");
        return view;
    }
    @RequestMapping("doedit")
    public ModelAndView doEdit(String password,HttpServletRequest request){
        StoreSellerVo sellerVo= (StoreSellerVo)request.getSession().getAttribute("sellerInfo");
        Member member = new Member();
        member.setMemberId(sellerVo.getMemberId());
        member.setMemberPasswd(DigestUtils.md5Hex(password));
        memberServiceImpl.updateMemberBaseInfo(member);
        ModelAndView modelAndView = new ModelAndView("message");
        modelAndView.addObject("msg", "密码修改成功");
        return modelAndView;
    }
}
